package com.fhzn.auth.entity;

import com.fhzn.auth.constant.Constants;
import com.fhzn.auth.mapper.OperateLogMapper;
import com.fhzn.auth.mapper.RoleMapper;
import com.fhzn.auth.web.request.UserRoleRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author heluo
 * 操作日志管理类
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OperateLogManager {

    private final OperateLogMapper operateLogMapper;
    private final RoleMapper roleMapper;


    /**
     * 记录用户角色分配操作日志
     *
     * @param request 用户角色请求
     */
    public void onUserRoleChange(UserRoleRequest request) {
        List<Role> rolesInDb = roleMapper.findRolesByNickname(request.getTargetUser());
        List<Integer> roleIds = rolesInDb.stream().map(Role::getId).collect(Collectors.toList());
        String objAfter = StringUtils.join(roleIds, ",");
        OperateLog operateLog = OperateLog.builder()
                .handler(request.getOperatorUser())
                .operateSection(Constants.UESR_SECTION)
                .operateMethod(Constants.USER_CONFIG_ROLES_ASSIGN)
                .operateTarget(request.getTargetUser())
                .modifyBeforeContent(StringUtils.EMPTY)
                .modifyAfterContent(StringUtils.substring(objAfter, 0, 1000))
                .loginSystem(request.getInvokeAppName())
                .build();
        operateLogMapper.insert(operateLog);
    }

}
